<template>
  <div class="abstract-reading">
    <!-- 左侧对话列表 -->
    <div class="audio-data-area" v-if="isHistoryCollapsed">
      <div class="conversation-list">
        <h3 class="list-item">历史记录</h3>
        <ul >
          <li v-for="(item, index) in recentConversations" :key="index" class="list-item-li"
            @click="showContent(item.id)">
            {{ item.title }}
          </li>
        </ul>
      </div>
    </div>
    
   
    <!-- 中间公文配置 -->
    <div class="audio-data-areaCenter" v-if="falgList"
      :style="{
        'background-color': '#061428', 
        'color': 'white',
        'position': 'relative',
        'width': isHistoryCollapsed ? '20%' : '18%',
        'min-height': '100%'
      }">
      <img @click="fold"  v-if="isHistoryCollapsed" class="icon-fold-fold cursor-p" src="../../assets/images/收缩.png" alt="收缩" title="收缩">
      <img @click="unfold" v-else class="icon-fold-fold cursor-p" title="展开"  src="../../assets/images/展开.png" alt="展开">
      <el-row type="flex" align="middle" class="mb-20">
        <!-- <el-col :span="4">
          <el-image
            style="width: 40px; height: 40px"
            src="https://fuss10.elemecdn.com/e/5d/4a731a90594a4af544c0c25941171jpeg.jpeg"
          ></el-image>
        </el-col> -->
        <el-col class="font-w fonts-20">{{ centerTop.name }}</el-col>
      </el-row>
      <el-row class="fonts-18 mb-10">{{ centerTop.desc }}</el-row>
      <!-- 核心内容 -->
      <el-row type="flex">
          <img class="mr-10" style="display: block; width: 30px; height: 30px" src="@/assets/images/组icon.png"></img>
          <h4>核心内容</h4>
        </el-row>
      <div class="core-content">
     
        <el-collapse v-model="activeNames" :accordion="false"  >
          <el-collapse-item title="标题名称" name="1">
            <div class="title-container">
              <el-input type="textarea" placeholder="请输入标题名称" v-model="center.title" :rows="5">
              </el-input>
              <!-- <div class="template-listcontent">
                <el-button type="primary" @click="nextStep(activeNames)" style="margin-bottom: -28px"><span
                    class="spanlistnr"> 下一步 </span></el-button>
              </div> -->
            </div>
          </el-collapse-item>
          <el-collapse-item title="内容概述" name="2">
            <div class="title-container">
              <el-input v-loading="descLoading" id="quickScrollFlag" type="textarea" placeholder="请输入内容概述"
                v-model="center.desc" :rows="5">
              </el-input>
              <div class="template-listcontent">
                <div class="quick-tip">
                  <img src="@/assets/images/快速生成.png"></img>
                  <span @click="quickSc('内容概述')">快速生成</span>
                </div>
                <!-- <el-button type="primary" @click="nextStep(activeNames)" style="margin-bottom: -28px"><span
                    class="spanlistnr"> 下一步 </span></el-button> -->
              </div>
            </div>
          </el-collapse-item>
          <el-collapse-item title="大纲" name="3">
            <div class="title-container">
              <!-- <el-input type="textarea" placeholder="请输入大纲" v-model="center.outline" :rows="5">
              </el-input> -->
              <vue-markdown id="quickoutScrollFlag" v-loading="outlineLoading"
                style="width:100%;height: 150px;overflow-y: auto;" :source="center.outline" :html="true"></vue-markdown>
              <div class="template-listcontent">
                <div class="quick-tip">
                  <img src="@/assets/images/快速生成.png"></img>
                  <span @click="quickSc('大纲')">快速生成</span>
                </div>
                <!-- <el-button type="primary" @click="nextStep(activeNames)" style="margin-bottom: -28px"><span
                    class="spanlistnr"> 下一步 </span></el-button> -->
              </div>
            </div>
          </el-collapse-item>
          <!-- <el-collapse-item title="知识库" name="4">
            <div>
              <el-select v-model="selectedKnowledgeBase" placeholder="请选择知识库" style="width: 100%">
                <el-option v-for="item in knowledgeBases" :key="item.value" :label="item.label" :value="item.value">
                </el-option>
              </el-select>
              <div style="margin-top: 20px">
                <span>自定义参考文件:</span>
              </div>
              <div style="position: fixed; top: 450px; left: 455px">
                <el-button type="primary" @click="addReferenceFile">+添加</el-button>
                <el-button type="primary" @click="nextStep(activeNames)">下一步</el-button>
              </div>
              <ul>
                <li v-for="(file, index) in referenceFiles" :key="index" style="margin-top: 10px">
                  {{ file.name }}
                  <el-button type="text" @click="deleteReferenceFile(index)">删除</el-button>
                </li>
              </ul>
            </div>
          </el-collapse-item> -->
        </el-collapse>
      </div>

      <!-- 文章配置 -->
      <div class="article-configuration">
        <el-row type="flex">
          <img class="mr-10" style="display: block; width: 30px; height: 30px" src="@/assets/images/组icon.png"></img>
          <h4>文章配置</h4>
        </el-row>
        <div class="word-count-container">
          <label for="word-count">篇幅</label>
          <el-input v-model="wordCount" placeholder="请输入篇幅" style="width: 100%"></el-input>
        </div>
      </div>
      <div class="template-list-itemStart "  style="position: absolute; bottom: 0; width: 90%;" >
        <span class="wordspan" @click="startWord(startType)">{{
          startType == 0 ? "开始生成" : "重新生成"
        }}</span>
      </div>
    </div>
    <el-container style="height: 100%; width: 65%;position: relative;"
   
    >
      <img @click="fold"  v-if="isHistoryCollapsed&&home" class="icon-fold-fold-home cursor-p" src="../../assets/images/收缩.png" alt="收缩" title="收缩">
      <img @click="unfold" v-else-if="!isHistoryCollapsed&&home" class="icon-fold-fold-home cursor-p" title="展开"  src="../../assets/images/展开.png" alt="展开">
      <el-main style="background-color: #061428; color: #fff">
        <!-- 是否首页选择模板页面 -->
        <el-row v-if="home">
          <el-row style="margin-top: 5%">
            <img src="@/assets/images/组7224.png" alt="" />
          </el-row>
          <el-row style="margin-top: 1%"> 公文拟呈 </el-row>
          <el-row style="margin-top: 1%"> 选题、成文、一站式生成 </el-row>
          <el-row style="margin-top: 5%">
            <el-col :span="24" class="modelList">
              <div class="scroll-container" ref="scrollWrap">
                <div class="scroll-content">
                  <div v-for="(item, index) in modelList" :key="index" class="modelbox"
                    @click="selectModel(item, item.id)">
                    <img v-if="curModel == item.id" src="~@/assets/images/curModel.png" />
                    <img v-else src="~@/assets/images/preModel.png" />
                    <p :title="item.doctype">{{ item.doctype }}</p>
                  </div>
                </div>
              </div>
            </el-col>
          </el-row>
        </el-row>
        <!-- 是否展示生成公文 -->
        <el-row style="text-align: left" v-if="gwShow">
          <div class="btnLine">
       
          <el-button
            @click="toHome"
            type="text"
            class="homeIcon"
            title="回到首页"
          ></el-button>
        </div>
          <div class="generated-report">
            <div class="generated-report-header" :style="{ height: isReferencesExpanded ? 'auto' : '50px' }"
            >
              <div class="references-section">
                <el-row type="flex" align="middle" justify="space-between">
                  <div class="font-w fonts-16">基于0篇参考文献</div>

                  <div @click="toggleReferences" style="cursor: pointer">
                    <i :class="isReferencesExpanded ? 'el-icon-arrow-up fonts-18' : 'el-icon-arrow-down fonts-18'"></i>
                  </div>
                </el-row>
                <transition name="slide">
                  <!-- <div class="reference-items" v-show="isReferencesExpanded">
                    <div style="position: relative" v-for="(ref, index) in referenceLiterature" :key="index"
                      class="reference-item">
                      <p>{{ ref.title }}</p>
                      <div class="circle-index">
                        {{ index + 1 }}
                      </div>
                    </div>
                  </div> -->
                  <el-empty :image-size="50" description="暂无参考文献"></el-empty>
                </transition>

              </div>
            </div>
            <div style="overflow-y: auto; position: relative" class="meetingMinutesCount" @mouseup="handleTextSelection"
              id="scrollFlag">
              <!-- 渲染markdown -->
              <div>
                <vue-markdown id="word" :source="right.meetingMinutesCount" :html="true"></vue-markdown>
              </div>
              <!-- 生成公文时展示 -->
              <div v-if="chunkFlag" class="generate-report-loading">
                <span class="prefix-margin">文章生成中 <i class="el-icon-loading"></i></span>

                <span class="span" @click="stopGeneration">停止生成</span>
              </div>
              <!-- 下方对整篇操作的按钮 -->
              <el-row v-if="bottomBtnFlag" style="margin-top: 10px;" type="flex">
                <el-col :span="1">
                  <el-tooltip effect="dark" content="语音朗读" placement="top">
                    <img @click="voice" class="cursor-p" src="@/assets/images/声音.png" />
                  </el-tooltip>
                </el-col>
                <el-col :span="1">
                  <el-tooltip effect="dark" content="重新生成" placement="top">
                    <img @click="startWord(1)" class="cursor-p" src="@/assets/images/刷新.png" />
                  </el-tooltip>
                </el-col>
                <el-col :span="1">
                  <el-tooltip effect="dark" content="复制" placement="top">
                    <img @click="copyContent" class="cursor-p" src="@/assets/images/复制.png" />
                  </el-tooltip>
                </el-col>
                <el-col :span="1">
                  <el-tooltip effect="dark" content="下载" placement="top">
                    <img @click="downloadPage" class="cursor-p" src="@/assets/images/下载.png" />
                  </el-tooltip>
                </el-col>
                <el-col :span="1">
                  <el-tooltip effect="dark" content="保存" placement="top">
                    <img @click="save" class="cursor-p" src="@/assets/images/公文.png" />
                  </el-tooltip>
                </el-col>
              </el-row>
            </div>
            <!-- 是否展示按钮菜单 -->
            <div ref="meetingMinutesContainer" class="generated-report-footer" :style="{
              position: 'absolute',
              left: buttonPosition.left + 'px',
              top: buttonPosition.top + 'px',
              display: 'flex',
              flexDirection: 'column',
              alignItems: 'flex-start',
            }">
              <!-- 是否展示图标和操作栏 -->

              <div style="z-index: 99" v-if="imgflag">
                <img style="cursor: pointer; width: 20px; height: 20px" src="@/assets/images/组111.png" alt="" />
                <div class="generated-report-footer-right">
                  <div class="hover-item" @click="handleOptionClick('润色')">
                    <img class="mr-5" style="width: 20px; height: 20px" src="@/assets/images/润色.png" alt="" />
                    <span>润色</span>
                  </div>

                  <div class="hover-item" @click="handleOptionClick('扩写')">
                    <img class="mr-5" style="width: 20px; height: 20px" src="@/assets/images/扩写.png" alt="" />
                    <span>扩写</span>
                  </div>

                  <div class="hover-item" @click="handleOptionClick('简写')">
                    <img class="mr-5" style="width: 20px; height: 20px" src="@/assets/images/简写.png" alt="" />
                    <span>简写</span>
                  </div>

                  <div class="hover-item" @click="handleOptionClick('续写')">
                    <img class="mr-5" style="width: 20px; height: 20px" src="@/assets/images/续写.png" alt="" />
                    <span>续写</span>
                  </div>


                </div>
              </div>

              <!-- 是否展示编辑栏 -->

              <div v-if="editOperate" class="edit-operate-panel">
                <div v-loading="editTextLoading" v-html="right.editText" id="editScrollFlag" class="generate-text">
                </div>
                <div v-if="bottomEditOperate" class="generate-button">
                  <span @click="replaceOriginalText" class="span replace-margin">替换原文</span>
                  <span @click="insertBelowText" class="span">插入下方</span>
                  <span @click="delSC" class="span">弃用</span>
                  <span @click="refreshSC" class="span">重试</span>
                </div>
              </div>
            </div>
          </div>
        </el-row>
      </el-main>
    </el-container>
  </div>
</template>
<script>
import axios from "axios";
import VueMarkdown from "vue-markdown";
import BScroll from "better-scroll";
export default {
  components: {
    VueMarkdown,
  },
  data () {
    return {
      uploadModal: {
        Visible: false,
      },
      fileMeetingList: [],
      meetinguid: null,
      dialogVisible: false,
      inputValue: "",
      isHistoryCollapsed: true, // 默认设置为收缩状态
      recentConversations: [
        "自定义XXXXXXXXXX",
        "自定义XXXXXXXXXX",
        "自定义XXXXXXXXXX",
        "自定义XXXXXXXXXX",
      ],
      modelList: [
        {
          id: "1",
          doctype: "通知",
        },
        {
          id: "2",
          doctype: "函件",
        },
        {
          id: "3",
          doctype: "请示",
        },
        {
          id: "4",
          doctype: "报告",
        },
        {
          id: "5",
          doctype: "其他",
        },
        {
          id: "6",
          doctype: "其他",
        },
      ],
      curModel: null, //模版当前点击
      falgList: false, //是否显示公文配置
      activeNames: ["1", "2", "3"],

      selectedKnowledgeBase: "", // 选中的知识库
      knowledgeBases: [
        // { value: 1, label: "政策法规" },
        // { value: 2, label: "规章制度" },
        // { value: 3, label: "标准规范" },
        // { value: 4, label: "理论研究成果" },
        // { value: 5, label: "领导讲话" },
        // { value: 6, label: "会议资料" },
        // { value: 7, label: "办文资料" },
        // { value: 8, label: "书籍资料" },
      ],
      referenceFiles: [],
      wordCount: "",
      showGeneratedReport: false,
      container: true,
      referenceLiterature: [
        { title: "文献标题", id: "1" },
        { title: "文献标题", id: "2" },
        { title: "文献标题", id: "3" },
        { title: "文献标题", id: "4" },
        { title: "文献标题", id: "5" },
      ],
      imgflag: false, //选中文字展示按钮
      wordCountParms: [],
      home: true, //是否展示首页模板
      gwShow: false, //是否展示生成公文
      left: {},
      centerTop: {
        name: "", //公文类型
        desc: "", //公文标题
      },
      center: {
        title: "中药材相关", //标题名称 中药材相关
        desc: "", //内容概述
        outline: "", //大纲
      },
      showFooterButton: false, // 是否显示按钮
      buttonPosition: { left: 0, top: 0 }, // 操作栏按钮的位置
      editPanelPosition: { left: 0, top: 0 }, // 编辑栏的位置
      right: {
        meetingMinutesCount: "", //公文
        selectText: "", // 选中的文字
        range: {}, //选中的对象
        editText: "", //修改的文字
      },
      chunkFlag: false,
      editOperate: false, // 是否展示编辑操作
      bottomBtnFlag: false, //最底部操作按钮
      startType: 0, //0为开始生成 1为重新生成
      streamReader: null, // 添加streamReader引用
      optionType: "", //润色 //扩写 //简写 //续写
      bottomEditOperate: false,
      isReferencesExpanded: false, // 控制参考文献列表展开状态
      descLoading: false, //内容概述loading
      outlineLoading: false, //大纲概述
      editTextLoading: false //生成的替换的文字
    };
  },
  watch: {
  },
  mounted () {
    this.$nextTick(() => {
        this.initScroll();
      });
    this.getGWList();
    document.addEventListener("click", this.handleDocumentClick);
  },
  beforeDestroy () { },
  methods: {
    parseMarkdown (markdownText) {
      if (!markdownText) return '';
      // 创建临时div元素处理HTML标签
      const tempDiv = document.createElement('div');
      tempDiv.innerHTML = markdownText;
      let html = tempDiv.textContent || tempDiv.innerText || '';
      // 简单实现markdown转HTML
      html = html
        // 标题
        .replace(/^#+\s*(.*?)\s*$/gm, '$1\n')
        // 加粗和斜体
        .replace(/\*\*(.*?)\*\*/g, '$1')
        .replace(/\*(.*?)\*/g, '$1')
        // 链接
        .replace(/\[(.*?)\]\(.*?\)/g, '$1')
        // 图片
        .replace(/!\[(.*?)\]\(.*?\)/g, '$1')
        // 代码块
        .replace(/```[\s\S]*?```/g, '')
        // 行内代码
        .replace(/`(.*?)`/g, '$1')
        // 列表
        .replace(/^\s*[\*\-+]\s+/gm, '')
        // 换行和多余空格
        .replace(/\n+/g, '\n')
        .replace(/\s+/g, ' ')
        .trim();

      return html;
    },
    // 选择模板事件
    selectModel(item, id) {
      this.curModel = id;
      this.centerTop.name = item.doctype;
      this.centerTop.desc = item.title;
      this.falgList = true;
      this.home = false;
      this.isHistoryCollapsed = false; // 保持自动收缩逻辑
    },
    // 滚动条
    initScroll () {
      var scrollWrap = this.$refs.scrollWrap;
      if (scrollWrap) {
        this.scroll = new BScroll(scrollWrap, {
          scrollX: true,
          scrollY: false,
          click: true,
          probeType: 5,
          mouseWheel: true, // 鼠标滚轮滚动
          disableMouse: false, // 启用鼠标拖动
          disableTouch: false, // 启用手指触摸
        });
      }
    },

    // 开始生成/重新生成
    startWord (type) {
      if (type == 0) {
        // 开始生成
        this.scrollToBottom();
        this.startType = 1;
        const wordCountParms = {
          ...this.center,
          requestid: "",
          maxnum: 2000, // 最大字数
          doctype: this.centerTop.name, // 文档类型
        };
        fetch("/gt/chat/createdocwithoutline", {
          method: "POST",
          body: JSON.stringify(wordCountParms),
          headers: {
            "Content-Type": "application/json",
          },
        })
          .then((response) => {
            this.gwShow = true;
            this.chunkFlag = true;
            if (!response.ok) {
              throw new Error("Network response was not ok");
            }
            return response.body; // 获取流式响应
          })
          .then((stream) => {
            this.streamReader = stream.getReader();
            const decoder = new TextDecoder("utf-8");
            let accumulatedData = ""; // 用于存储完整的字符串
            const read = () => {
              return this.streamReader.read().then((result) => {
                if (result.done) {
                  this.chunkFlag = false;
                  this.bottomBtnFlag = true;
                  return;
                }
                this.scrollToBottom();
                const chunk = decoder.decode(result.value, { stream: true });
                accumulatedData += chunk; // 累积数据
                // this.right.meetingMinutesCount = this.$parsedMarkdown(accumulatedData); // 渲染最终数据
                this.right.meetingMinutesCount = accumulatedData // 渲染最终数据
                return read(); // 继续读取下一块数据
              });
            };
            read();
          });
      } else if (type == 1) {
        // 重新生成
        this.scrollToBottom();
        this.gwShow = false;
        this.chunkFlag = false;
        this.bottomBtnFlag = false;
        const wordCountParms = {
          ...this.center,
          requestid: "",
          maxnum: 2000, // 最大字数
          doctype: this.centerTop.name, // 文档类型
        };
        fetch("/gt/chat/createdocwithoutline", {
          method: "POST",
          body: JSON.stringify(wordCountParms),
          headers: {
            "Content-Type": "application/json",
          },
        })
          .then((response) => {
            this.gwShow = true;
            this.chunkFlag = true;
            if (!response.ok) {
              throw new Error("Network response was not ok");
            }
            return response.body; // 获取流式响应
          })
          .then((stream) => {
            this.streamReader = stream.getReader();
            const decoder = new TextDecoder("utf-8");
            let accumulatedData = ""; // 用于存储完整的字符串
            const read = () => {
              return this.streamReader.read().then((result) => {
                if (result.done) {
                  this.chunkFlag = false;
                  this.bottomBtnFlag = true;
                  return;
                }
                this.scrollToBottom();
                const chunk = decoder.decode(result.value, { stream: true });
                accumulatedData += chunk; // 累积数据
                // this.right.meetingMinutesCount = this.$parsedMarkdown(accumulatedData); // 渲染最终数据
                this.right.meetingMinutesCount = accumulatedData // 渲染最终数据
                return read(); // 继续读取下一块数据
              });
            };
            read();
          });
      }
    },
    // 停止生成
    stopGeneration () {
      if (this.streamReader) {
        this.streamReader.cancel(); // 取消流式读取
        this.streamReader = null;
        this.chunkFlag = false;
        this.bottomBtnFlag = true;
      }
    },
    // 保存公文
    save () {
      axios({
        method: "post",
        url: `/gt/chat/savedoc`,
        data: {
          content: this.right.meetingMinutesCount,
          doctype: this.centerTop.name,
          title: this.center.title,
          docdesc: this.center.desc,
          outline: this.center.outline,
        },
      }).then((res) => {
        if (res.data.success) {
          this.$message.success("保存成功!");
          this.getGWList()
        } else {
          this.$message.error(res.data.msg);
        }
      });
    },
    // 获取模板列表
    getList () {
      axios({
        method: "get",
        url: `/gt/util/querytemplatelist?templatetype=` + "doc",
      }).then((res) => {
        if (res.data.success) {
          this.modelList = res.data.data;
        } else {
          this.$message.error(res.data.msg);
        }
      });
    },
    // 获取历史记录(公文列表)
    getGWList () {
      axios({
        method: "get",
        url: `/gt/chat/querydoclist`,
      }).then((res) => {
        if (res.data.success) {
          if (res.data.data.length == 0) {
            this.$message.warning("暂无历史记录!");
          } else {
            this.recentConversations = res.data.data;
          }
        } else {
          this.$message.error(res.data.msg);
        }
      });
    },

    // 点击下一步方法
    // nextStep (activeNames) {
    //   if (activeNames[0] == "1") {
    //     // 打开内容概述
    //     this.activeNames = ["2"];
    //   } else if (activeNames[0] == "2") {
    //     // 打开大纲
    //     this.activeNames = ["3"];
    //   } else if (activeNames[0] == "3") {
    //     // 打开知识库
    //     this.activeNames = ["4"];
    //   }
    // },
    // 快速生成
    quickSc (type) {
      this.quickScrollToBottom()
      const data = {
        requestid: "",
        query: this.center.title,
      };
      if (type == "内容概述") {
        this.descLoading = true
        this.center.desc = ''
        fetch("/gt/chat/createdesc", {
          method: "POST",
          body: JSON.stringify(data),
          headers: {
            "Content-Type": "application/json",
          },
        })
          .then((response) => {
            this.descLoading = false
            if (!response.ok) {
              throw new Error("Network response was not ok");
            }
            return response.body; // 获取流式响应
          })
          .then((stream) => {
            const reader = stream.getReader();
            const decoder = new TextDecoder("utf-8");
            const read = () => {
              return reader.read().then((result) => {
                if (result.done) {
                  return;
                }
                this.quickScrollToBottom()
                const chunk = decoder.decode(result.value, { stream: true });
                this.center.desc += this.parseMarkdown(chunk); // 渲染最终数据
                // this.center.desc = this.$parsedMarkdown(accumulatedData); // 渲染最终数据
                return read(); // 继续读取下一块数据
              });
            };
            read();
          });
      } else if (type == "大纲") {
        this.quickoutScrollToBottom()
        this.center.outline = ''
        this.outlineLoading = true
        fetch("/gt/chat/createoutline", {
          method: "POST",
          body: JSON.stringify(data),
          headers: {
            "Content-Type": "application/json",
          },
        })
          .then((response) => {
            this.outlineLoading = false
            if (!response.ok) {
              throw new Error("Network response was not ok");
            }
            return response.body; // 获取流式响应
          })
          .then((stream) => {
            const reader = stream.getReader();
            const decoder = new TextDecoder("utf-8");
            const read = () => {
              return reader.read().then((result) => {
                if (result.done) {
                  return;
                }
                this.quickoutScrollToBottom()
                const chunk = decoder.decode(result.value, { stream: true });
                // this.center.outline += this.parseMarkdown(chunk); // 渲染最终数据
                this.center.outline += chunk; // 渲染最终数据
                return read(); // 继续读取下一块数据
              });
            };
            read();
          });
      }
    },
    // 点击历史记录回显
    showContent (id) {
      this.home = false;
      this.falgList = true;
      this.gwShow = true;
      this.bottomBtnFlag = true;
      axios({
        method: "get",
        url: `/gt/chat/querydocbyid?docid=${id}`,
      }).then((res) => {
        if (res.data.success) {
          const obj = res.data.data[0];
          this.centerTop.name = obj.doctype;
          this.centerTop.desc = obj.title;
          this.center.title = obj.title;
          this.center.desc = obj.docdesc;
          this.center.outline = obj.outline;
          this.startType = obj.content ? 1 : 0;
          this.right.meetingMinutesCount = obj.content;
        } else {
          this.$message.error(res.data.msg);
        }
      });
    },
    // 选中文字事件
    handleTextSelection () {
      const selection = window.getSelection();
      if (selection.toString().length > 0) {
        const range = selection.getRangeAt(0);
        const rect = range.getBoundingClientRect();
        this.imgflag = true;
        this.buttonPosition = {
          left: rect.left - 700, // 调整到选中文字左侧
          top: rect.top + window.scrollY,
        };
        // 保留选中的文字
        this.right.selectText = selection.toString();
        this.right.range = range;
      } else {
        // 没有选中文字时关闭按钮
        this.imgflag = false;
      }
    },
    //选中操作栏按钮
    handleOptionClick (option) {
      this.editTextLoading = true
      this.editScrollToBottom();
      this.optionType = option;
      // this.imgflag = false;
      this.editOperate = true;
      const data = {
        title: this.center.title,
        doctype: this.centerTop.name,
        content: this.right.selectText,
        command: this.optionType, //
        requestid: "",
      };
      fetch("/gt/chat/doccommand", {
        method: "POST",
        body: JSON.stringify(data),
        headers: {
          "Content-Type": "application/json",
        },
      })
        .then((response) => {
          this.editTextLoading = false
          if (!response.ok) {
            throw new Error("Network response was not ok");
          }
          return response.body; // 获取流式响应
        })
        .then((stream) => {
          const reader = stream.getReader();
          const decoder = new TextDecoder("utf-8");
          const read = () => {
            return reader.read().then((result) => {
              if (result.done) {
                this.bottomEditOperate = true;
                return;
              }
              this.editScrollToBottom();
              const chunk = decoder.decode(result.value, { stream: true });
              this.right.editText += chunk; // 渲染最终数据
              return read(); // 继续读取下一块数据
            });
          };
          read();
        });
    },
    // 鼠标点击其他区域
    handleDocumentClick (e) {
      const selection = window.getSelection();
      const isOptionClick = e.target.closest(".generated-report-footer-right");
      const isEditPanelClick = e.target.closest(".edit-operate-panel");
      if (selection.toString().length === 0) {
        this.imgflag = false;
      }
      if (!isOptionClick && !isEditPanelClick) {
        // 点击非选项区域和非编辑面板时关闭编辑面板
        this.editOperate = false;
        // this.right.selectText = "";
        // this.right.editText = "";
        // this.right.range = {};
      }
    },
    //替换原文
    replaceOriginalText () {
      this.right.range.deleteContents();
      this.right.range.insertNode(document.createTextNode(this.right.editText));
      this.editOperate = false; // 替换完成后关闭编辑面板
      this.right.selectText = "";
      this.right.editText = "";
      this.right.range = {};
    },
    //插入下方
    insertBelowText () {
      this.right.range.insertNode(document.createTextNode(this.right.editText));
      // this.right.meetingMinutesCount += this.right.editText;
      this.editOperate = false; // 插入完成后关闭编辑面板
      this.right.selectText = "";
      this.right.editText = "";
      this.right.range = {};
    },
    // 弃用生成的文字
    delSC () {
      this.right.editText = "";
      this.editOperate = false; // 插入完成后关闭编辑面板
      this.right.selectText = "";
      this.right.editText = "";
      this.right.range = {};
    },
    // 重试
    refreshSC () {
      this.editTextLoading = true
      this.editScrollToBottom();
      // this.bottomEditOperate = false;
      this.right.editText = "";
      const data = {
        title: this.center.title,
        doctype: this.centerTop.name,
        content: this.right.selectText,
        command: this.optionType,
        requestid: "",
      };
      fetch("/gt/chat/doccommand", {
        method: "POST",
        body: JSON.stringify(data),
        headers: {
          "Content-Type": "application/json",
        },
      })
        .then((response) => {
          this.editTextLoading = false
          if (!response.ok) {
            throw new Error("Network response was not ok");
          }
          return response.body; // 获取流式响应
        })
        .then((stream) => {
          const reader = stream.getReader();
          const decoder = new TextDecoder("utf-8");
          const read = () => {
            return reader.read().then((result) => {
              if (result.done) {
                this.bottomEditOperate = true;
                return;
              }
              this.editScrollToBottom();
              const chunk = decoder.decode(result.value, { stream: true });
              this.right.editText += chunk; // 渲染最终数据
              return read(); // 继续读取下一块数据
            });
          };
          read();
        });
    },
    // 复制
    copyContent () {
      const textarea = document.createElement("textarea");
      textarea.value = this.right.meetingMinutesCount;
      document.body.appendChild(textarea);
      textarea.select();
      document.execCommand("copy");
      document.body.removeChild(textarea);
      this.$message.success("复制成功");
    },
    //公文滚动到底部
    scrollToBottom () {
      this.$nextTick(() => {
        setTimeout(() => {
          var div = document.getElementById("scrollFlag");
          if( div.scrollHeight){
            div.scrollTop = div.scrollHeight;
          }
        }, 500);
      });
    },
    // 润色滚动到底部
    editScrollToBottom () {
      this.$nextTick(() => {
        setTimeout(() => {
          var div = document.getElementById("editScrollFlag");
          if( div.scrollHeight){
            div.scrollTop = div.scrollHeight;
          }
        }, 500);
      });
    },
    // 内容概述快速生成
    quickScrollToBottom () {
      this.$nextTick(() => {
        setTimeout(() => {
          var div = document.getElementById("quickScrollFlag");
          if( div.scrollHeight){
            div.scrollTop = div.scrollHeight;
          }
        }, 500);
      });
    },
    // 大纲快速生成
    quickoutScrollToBottom () {
      this.$nextTick(() => {
        setTimeout(() => {
          var div = document.getElementById("quickoutScrollFlag");
          if( div.scrollHeight){
            div.scrollTop = div.scrollHeight;
          }
        }, 500);
      });
    },

    // 下载
    downloadPage () {
      const content = this.right.meetingMinutesCount;
      const blob = new Blob([content], { type: "application/msword" });
      const url = URL.createObjectURL(blob);
      const a = document.createElement("a");
      a.href = url;
      a.download = `${this.center.title}文档.doc`;
      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a);
      URL.revokeObjectURL(url);
      this.$message.success("下载成功");
    },
    // 语音朗读
    voice () {
      this.$message.success("正在朗读文本!");
      if (window.speechSynthesis.speaking) {
        this.$message.warning("当前正在朗读文本!");
        return;
      }
      // 为了防止在暂停状态下转语音，调用前设置继续播放
      window.speechSynthesis.resume();
      // 设置播放
      var textArea = document.getElementById('word');
      var range = document.createRange();
      range.selectNodeContents(textArea);
      var speech = new SpeechSynthesisUtterance();
      speech.text = this.right.meetingMinutesCount; // 内容
      speech.lang = "zh-cn"; // 语言
      speech.voiceURI = "Microsoft Huihui - Chinese (Simplified, PRC)"; // 声音和服务
      speech.volume = 0.7; // 声音的音量区间范围是​​0​​​到​​1默认是​​1​​
      speech.rate = 1; // 语速，数值，默认值是​​1​​​，范围是​​0.1​​​到​​10​​​，表示语速的倍数，例如​​2​​表示正常语速的两倍
      speech.pitch = 1; // 表示说话的音高，数值，范围从​​0​​​（最小）到​​2​​​（最大）。默认值为​​1​​。
      window.speechSynthesis.speak(speech);
    },
    // 切换文献列表有无
    toggleReferences () {
      this.isReferencesExpanded = !this.isReferencesExpanded;
    },
       // 回到首页
       toHome() {
      this.$router.push({ path: "/home" });
    },

    // 历史记录展开
    fold() {
      this.isHistoryCollapsed = false;
    },
    // 历史记录收缩
    unfold() {
      this.isHistoryCollapsed = true;
    },
  },
};
</script>

<style scoped lang="less">
/deep/.el-select-dropdown {
  position: absolute;
  z-index: 1001;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  background-color: #061428;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  box-sizing: border-box;
  margin: 5px 0;
}

/deep/.el-select-dropdown__list {
  list-style: none;
  padding: 6px 0;
  margin: 0;
  box-sizing: border-box;
  background-color: #061428;
}

.outline-list {
  li {
    margin-top: 15px;
  }
}

.core-content .template-list .el-button[data-v-0f5bc162] {
  margin-right: 23px;
}

.template-listcontent {
  text-align: right;
  position: relative;
}

/deep/.el-collapse-item__wrap {
  will-change: height;
  background-color: #061428;
  overflow: hidden;
  box-sizing: border-box;
  border-bottom: 1px solid #096391;
}

.el-button--primary {
  background-color: #28608c;
  border-color: #2293d0 !important;
  width: 75px;
  letter-spacing: 3px;
  border-width: 1px;
  font-size: 12px;
  height: 30px;
  border-radius: 5px;
}

.abstract-reading {
  display: flex;
  height: 100vh;

  .el-aside {
    background-color: #061428;
    color: #fff;
    text-align: left;
  }

  .el-main {
    background-color: #061428;
    color: #fff;
    text-align: center;
  }
}



.audio-data-areaCenter {
  padding-bottom: 60px;
  overflow-y: auto;
  background-color: #061428;
  color: white;
  padding: 20px;
  box-sizing: border-box;
  border-right: 1px solid #096391;
  .conversation-list {
    margin-top: 15px;
    ul {
      list-style-type: none;
      padding: 0;
    }
  }
}

.image-container {
  position: relative;
  height: 300px;
  left: -40px;
  margin-top: 50px;
}

.image-bottom {
  position: absolute;
  top: 52px;
  left: 62px;
  z-index: 99;
}

.image-top {
  position: absolute;
  top: 20px;
  left: 17px;
  opacity: 1;
}

.caption {
  display: block;
  text-align: center;
  margin-top: 10px;
}

.btnsong {
  position: fixed;
  bottom: 4px;
  right: 19%;
}

.imgSearch {
  position: fixed;
  left: 315px;
  top: 22px;
}

.elHeader {
  text-align: left;
  font-size: 12px;
  background-color: #28608c;
  color: #fff;
  border-radius: 10px;
  width: 270px;
}

.list-item {
  color: #ffffff;
  margin: 0px 11px;
  margin-bottom: 10px;
  letter-spacing: 3px;
  font-size: 24px;
}

.list-item-li {
  font-size: 16px;
  padding: 10px;
  margin-bottom: 5px;
  color: white;
  letter-spacing: 3px;
  cursor: pointer;
}

.label {
  width: 130px;
  font-size: 16px;
  line-height: 24px;
  color: #fff;
}

.modelList {
  height: 331px;
  width: 92%;
  box-sizing: border-box;
  margin: 10px 4%;
  padding: 0 100px 30px 100px;
  margin-bottom: 38px;
  display: block;
  overflow: hidden;
  background: url("~@/assets/images/modelList-bg.png") no-repeat;
  background-position: center bottom;
  background-size: 100% auto;

  .scroll-container {
    width: 100%;
    overflow: hidden;
  }
  .scroll-content {
    height: 271px;
    display: flex;
    width: max-content;
  }

  .modelbox {
    width: 170px;
    height: 271px;
    background-color: lightblue;
    margin: 0px 25px;
    display: inline-block;
    overflow: hidden;
    background: url("~@/assets/images/modelbox-bg.png");
    background-size: 100% 100%;
    cursor: pointer;

    img {
      display: block;
      width: 126px;
      height: 131px;
      margin: 30px auto;
    }

    p {
      line-height: 24px;
      text-align: center;
      font-size: 18px;
      color: rgba(248, 252, 255, 0);
      line-height: 26px;
      text-shadow: 0px 3px 0px rgba(0, 103, 156, 0.33), 0px 3px 5px rgba(6, 13, 16, 0.7);
      background: linear-gradient(0deg, #7cd0ff 0%, #feffff 100%);
      background-clip: text;
      color: transparent;
      padding: 0 20px;
      display: -webkit-box;
      -webkit-line-clamp: 2;
      line-clamp: 2;
      -webkit-box-orient: vertical;
      overflow: hidden;
      text-overflow: ellipsis;
    }
  }
}

.core-content {
  background-color: #061428;
  padding: 10px;
  border: 1px solid #096391;
  max-height: 63vh;
  overflow-y: auto;
  .title-container {
    width: 96%;
    margin: 5px;
    .el-input {
      width: calc(100% - 250px);
    }

    .el-button {
      margin-left: 10px;
    }
  }

  .template-list {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-top: 10px;

    .el-button {
      margin-right: 10px;
    }
  }

  .template-list-item {
    margin-bottom: 10px;
    display: flex;
    line-height: 1.5;
    flex-direction: column;
    margin-left: 20px;
  }

  /deep/.el-collapse-item__header {
    background-color: #061428;
    color: #fff;
    font-size: 16px;
    font-weight: bold;
    border-bottom: 1px solid #061428;
  }

  /deep/.el-collapse-item__content {
    background-color: #061428;
    color: #fff;
    border: 1px solid #096391;
  }

  /deep/.el-textarea__inner {
    background-color: #061428;
    color: #fff;
    border: 1px solid #096391;
    border-radius: 20px;
    padding: 10px 20px;
    height: 130px !important;
    max-height: 200px;
    overflow-y: auto;
  }
}

/deep/.el-collapse-item__content {
  font-size: 13px;
  color: #c0c4cc;
  line-height: 1.77;
}

.spanlist {
  position: absolute;
  margin-left: -19px;
  margin-top: -4px;
}

.spanlistnr {
  position: absolute;
  margin-left: -19px;
  margin-top: -4px;
}

/deep/.el-dialog__header {
  padding: 5px 20px;
  background-color: #013f70;
  color: #fff;
  font-size: 18px;
  font-weight: bold;
  opacity: 0.9;
  border: 2px solid #26a9f9;
}

/deep/.el-dialog__body {
  padding: 20px;
  background-color: #020c14;
  border: 1px solid #26a9f9;
}

.btn {
  background-image: url("../../assets/intelligence/组1.png");
  background-size: 100% 100%;
  background-position: center;
  color: #fff;
  border: none;
  outline: none;
}

/deep/.btn.active.focus,
.btn.active:focus,
.btn.focus,
.btn:active.focus,
.btn:active:focus,
.btn:focus {
  outline: none;
  border: none;
}

/deep/.el-upload-dragger {
  background-color: #04223d;
  width: 38vw;
  border: 1px dashed #26a9f9;
}

/deep/ input[type="file"] {
  display: none;
}

.box {
  background-color: #020c14;
  padding: 20px;
  min-height: 100vh; 
}

/deep/.el-button--text {
  color: #fff;
}

.bg-color {
  background-color: #013f70;
}

.color-013f70 {
  color: #26a9f9;
  font-weight: 600;
}

/deep/.el-input__inner {
  background-color: #020c14;
  border: 1px solid #26a9f9;
  color: #fff;
  border-radius: 20px;
}

/deep/.el-input__inner:hover,
.el-input__inner:focus {
  border: 1px solid #26a9f9;
}

/deep/.el-button--primary:focus,
.el-button--primary:hover {
  background-color: #013f70;
  border-color: #013f70;
}



.template-list-itemStart {
  display: flex;
  justify-content: center;
  padding: 10px 0;
  background-color: #061428;
  z-index: 100;

}

.wordspan {
  color: #ffffff;
  width: 100%;
  background-color: #0B4880;
  text-align: center;
  height: 28px;
  line-height: 28px;
  border-radius: 10px;
  cursor: pointer;
  align-items: center;
}

.generated-report {
  background-color: #061428;
  color: white;
  h3,
  h4,
  h5 {
    color: #ffffff;
  }

  p {
    margin: 10px 0;
  }

  .text-center {
    text-align: center;
  }
}

.generate-report-loading {
  display: flex;
  justify-content: space-between;
  background-color: #061428;
  border: 1px solid #26a9f9;
  border-radius: 6px;
  height: 28px;
  line-height: 28px;
  align-items: center;
  padding: 20px;

  .span {
    border: 1px solid #26a9f9;
    width: 65px;
    border-radius: 8px;
    text-align: center;
    margin-right: 16px;
    cursor: pointer;
  }
}

.generated-report-header {
  height: 200px;
  border-radius: 12px;
  background-color: #0e2e50;
  opacity: 1;
  border: 1px solid #26a9f9;
  margin-bottom: 10px;

  .references-section {
    display: flex;
    flex-direction: column;
    flex-wrap: nowrap;
    padding: 10px;

    h4 {
      margin-bottom: 10px;
      color: #ffffff;
    }

    .reference-items {
      display: flex;
      flex-direction: row;
      gap: 10px;
      max-width: 100%;
      overflow-x: auto;
      scrollbar-width: thin;
      scrollbar-color: #26a9f9 #061428;
    }

    .reference-items::-webkit-scrollbar {
      height: 8px;
    }

    .reference-items::-webkit-scrollbar-track {
      background: #061428;
    }

    .reference-items::-webkit-scrollbar-thumb {
      background-color: #26a9f9;
      border-radius: 4px;
    }

    .reference-item {
      flex: 0 0 250px;
      text-align: center;
      background-color: #061428;
      border: 1px solid #26a9f9;
      border-radius: 8px;
      margin: 10px;
      height: 100px;
      text-align: center;

      p {
        text-align: left;
        color: #ffffff;
      }

      span {
        font-weight: bold;
        color: #ffffff;
      }
    }
  }
}

.report-container {
  display: flex;
  flex-direction: column;
  gap: 2ch;
}

.generated-report-footer {
  cursor: pointer;
}

.generated-report-footer-right {
  width: 100%;
  height: 150px;
  background-color: #061428;
  border: 1px solid #26a9f9;
  display: flex;
  flex-direction: column;
  justify-content: space-around;
  align-items: center;
  display: flex;
  gap: 8px;
  transition: all 0.3s ease;
  text-align: center;
}

.generated-report-footer-right .hover-item {
  color: #ffffff;
  cursor: pointer;
  padding: 4px 8px;
  transition: all 0.3s ease;
  width: 100%;
}

.generated-report-footer-right .hover-item:hover {
  width: 100%;
  background-color: #ccc;
}

.edit-operate-panel {
  width: 58vw;
}

.generate-text {
  height: 150px;
  background-color: #061428;
  border: 1px solid #26a9f9;
  border-radius: 10px;
}

.generate-button {
  height: 25px;
  background-color: #096a9b;
  border: 1px solid #26a9f9;
  border-radius: 6px;
  display: flex;
  justify-content: space-around;
  align-items: center;
  gap: 16px;
  margin-top: 8px;
  font-size: 12px;

  .span {
    border: 1px solid #26a9f9;
    width: 65px;
    border-radius: 8px;
    text-align: center;
    margin-right: 16px;
    cursor: pointer;
  }

  .span:last-child {
    margin-right: 0;
  }

  .span.replace-margin {
    margin-left: 2ch;
  }
}

.generate-text {
  background-color: #096a9b;
  border: 1px solid #26a9f9;
  border-radius: 6px;
  display: flex;
  gap: 16px;
  font-size: 12px;
  overflow-y: auto;
}

.nextspan {
  border: 1px solid #26a9f9;
  width: 65px;
  border-radius: 8px;
  text-align: center;
  margin-right: 16px;
  cursor: pointer;
}

.quick-tip {
  color: #2293d0;
  cursor: pointer;
}

.circle-index {
  position: absolute;
  right: 20px;
  bottom: 10px;
  background-color: #26a9f9;
  color: white;
  border-radius: 50%;
  width: 20px;
  height: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
}


.generated-report-header {
  transition: height 0.2s ease;
  overflow: hidden;
}

.slide-enter-active,
.slide-leave-active {
  transition: all 0.2s ease;
  max-height: 500px;
}

.slide-enter,
.slide-leave-to {
  max-height: 0;
  opacity: 0;
}

/deep/.el-loading-mask {
  background: none;
}
.btnLine {
  height: 24px;
  width: 100%;
  display: flex;
  justify-content: end;
  margin-bottom:10px ;

}
::v-deep .btnLine .el-button {
  width: 24px;
  height: 24px;
  margin-left: 14px;
  background-color: rgba(0, 0, 0, 0);
}
.homeIcon {
  background: url("~@/assets/images/首页.png") no-repeat;
  background-size: 100% 100%;
}
.icon-fold-fold{
  position: absolute;
  left:0%;
  top: 50%;
}
.icon-fold-fold-home{
  position: absolute;
  left: 0%;
  top: 50%;
}
.audio-data-area {
  width: 15%;
  background-color: #061428;
  color: rgb(27, 12, 12);
  padding: 20px;
  box-sizing: border-box;
  border-right: 1px solid #096391;
  .conversation-list {
    ul {
      list-style-type: none;
      padding: 0;
    }
  }
}
</style>
